package com.cheapflix.controller;

import com.cheapflix.beans.DVD;
import com.cheapflix.beans.User;
import com.cheapflix.dao.RecommendedDAO;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * Controller class that redirects to home page.
 * @author Group B
 */
@Controller
public class HomeController {

    RecommendedDAO rdao;
    private static final Logger logger=Logger.getLogger(HomeController.class);
    @Autowired
    public void init(RecommendedDAO rdao) {
        this.rdao = rdao;
    }

    @RequestMapping("/home")
    public ModelAndView home(HttpSession session) {
        logger.info("---------------- In Home ----------------");
        User me = (User) session.getAttribute("me");
        if(me==null){
            return new ModelAndView("redirect:/");
        }
        logger.info("Me: " + me);
        Set<DVD> movies = rdao.getMoviesRecommendedToMe(me.getId());
        Map< String, Integer > recommendedTimes = new HashMap< String, Integer >();
        for( DVD movie : movies ){
         int numtimes=   rdao.getNumberTimesFlickRecommendedToMe ( me.getId(),movie.getId() );
         recommendedTimes.put(movie.getId()+"", numtimes);
        }
        ModelAndView mav = new ModelAndView();
        mav.addObject("recommendationTimes",recommendedTimes);
        mav.setViewName("home");
        mav.addObject("movies", movies);
        return mav;
    }
}
